<?php

namespace app\modules\indexapi\controllers;

use yii\base\Model;
use yii\data\ActiveDataProvider;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBearerAuth;
use yii\rest\ActiveController;
use yii\rest\IndexAction;

class BaseActiveController extends ActiveController
{
    public function actions()
    {
        $actions = parent::actions();

        $actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];

        return $actions;
    }


    public function behaviors()
    {
        return array_merge(parent::behaviors(), [
            'authenticator' => [
                'class' => CompositeAuth::className(),
                'authMethods' => [
                    HttpBearerAuth::className()
                ],
            ],
        ]); // TODO: Change the autogenerated stub
    }

    public function prepareDataProvider(IndexAction $action, $filter)
    {

        $requestParams = \Yii::$app->getRequest()->getBodyParams();
        if (empty($requestParams)) {
            $requestParams = \Yii::$app->getRequest()->getQueryParams();
        }

        $query = $this->buildQuery();

        if (!empty($filter)) {
            $query->andFilterWhere($filter);
        }

        return \Yii::createObject([
            'class' => ActiveDataProvider::className(),
            'query' => $query,
            'pagination' => [
                'params' => $requestParams,
            ],
            'sort' => [
                'params' => $requestParams,
                'attributes' => $this->prepareSortAttributes(),
            ],
        ]);
    }

    /**
     * @return \yii\db\ActiveQueryInterface
     */
    protected function buildQuery(){
        /* @var $modelClass \yii\db\BaseActiveRecord */
        $modelClass = $this->modelClass;

        return $modelClass::find();
    }

    public function prepareSortAttributes()
    {
        /* @var $modelClass Model */
        $modelClass = $this->modelClass;
        $model = $modelClass::instance();
        $attributes = [];
        foreach ($model->attributes() as $attribute) {
            $attributes[$attribute] = [
                'asc' => [$attribute => SORT_ASC],
                'desc' => [$attribute => SORT_DESC],
                'label' => $model->getAttributeLabel($attribute),
            ];
        }

        return $attributes;
    }

    public function checkAccess($action, $model = null, $params = [])
    {
//        $oauthUser = $request->getOAuthUser();
//        $module = app()->http->getName();
//        $controller = $request->controller();
//        $action = $request->action();
//        if (!Enforcer::enforce('admin:' . $oauthUser->id, $module, $controller, $action)) {
//            throw new \yii\web\ForbiddenHttpException(sprintf('You can only %s articles that you\'ve created.', $action));
//        }
    }
}
